package com.basic.modules.nykf.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.aliyun.oss.common.utils.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.basic.common.utils.*;
import com.basic.modules.nykf.dao.JxSjDao;
import com.basic.modules.nykf.dao.ZzhFpGsDao;
import com.basic.modules.nykf.entity.*;
import com.basic.modules.nykf.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class ZzhFpGsServiceImpl extends ServiceImpl<ZzhFpGsDao, ZzhFpGsEntity> implements ZzhFpGsService {

    @Autowired
    ZzhFpGsDao zzhFpGsDao;

    @Autowired
    ZzhService zzhService;

    @Lazy
    @Autowired
    ZzhFpKfService zzhFpKfService;

    @Autowired
    JxSjService jxSjService;

    @Autowired
    JxSjDao jxSjDao;

    @Autowired
    CustomerShopBusinessService customerShopBusinessService;

    @Override
    public PageUtils getZzhFpgsList(ParamsModel<Map> params) {
        IPage<Map> page = new Query<Map>().getPage(BeanUtil.beanToMap(params.getPage()));
        IPage<Map> zzhFpgsList = baseMapper.getZzhFpgsList(page, params.getCondition());
        return new PageUtils(zzhFpgsList);
    }

    @Override
    public R postFpGsJxSjJy(ZzhFpGsEntity zzhFpGsEntity) {
        Date zzhFpgsKsrq = zzhFpGsEntity.getKsrq();
        Date zzhFpgsJsrq = zzhFpGsEntity.getJsrq();
        Long zzhId = zzhFpGsEntity.getZzhId();
        List<String> branchesWithPerformanceBySubAccount = jxSjDao.getBranchesWithPerformanceBySubAccount(DateUtils.format(zzhFpgsKsrq), DateUtils.format(zzhFpgsJsrq), zzhId);
        return R.ok(branchesWithPerformanceBySubAccount);
    }

    @Override
    public R postZzhFpgs(ZzhFpGsEntity zzhFpGsEntity) {
        Long zzhId = zzhFpGsEntity.getZzhId();

        // 获取输入的开始日期和结束日期
        Date zzhFpgsKsrq = zzhFpGsEntity.getKsrq();
        Date zzhFpgsJsrq = zzhFpGsEntity.getJsrq();
        boolean isPermanent = zzhFpgsJsrq.getTime() == 6879398400000L; // 判断是否为永久(2188年)

        // 校验1: 结束日期不能小于开始日期(除非结束日期是永久)
        if (zzhFpgsJsrq.compareTo(zzhFpgsKsrq) < 0) {
            return R.error("结束日期不能小于开始日期!");
        }

        // 获取业务相关信息
        ZzhEntity zzhObj = zzhService.getOne(new QueryWrapper<ZzhEntity>().eq("zzh_id", zzhId));
        CustomerShopBusinessEntity ywObj = customerShopBusinessService.getOne(
                new QueryWrapper<CustomerShopBusinessEntity>().eq("customer_shop_business_id", zzhObj.getCustomerShopBusinessId()));

        Date ywschzsj = ywObj.getYwschzsj(); // 业务首次合作时间
        Date ywjssj = ywObj.getYwjssj();     // 业务结束时间

        // 校验2: 开始日期必须大于等于业务首次合作日期
        if (zzhFpgsKsrq.compareTo(ywschzsj) < 0) {
            return R.error("分配开始时间不能小于该业务首次合作时间!");
        }

        // 校验3: 结束日期必须小于等于业务的结束日期(除非是永久)
        if (!isPermanent && zzhFpgsJsrq.compareTo(ywjssj) > 0) {
            return R.error("分配结束时间不能大于该业务结束时间!");
        }

        // 获取该账号下的所有历史分配记录
        QueryWrapper<ZzhFpGsEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("zzh_id", zzhId).orderByAsc("ksrq");
        List<ZzhFpGsEntity> fpList = this.list(queryWrapper);

        // 校验4: 检查时间段是否与历史分配重叠
        for (ZzhFpGsEntity existingFp : fpList) {
            Date existingKsrq = existingFp.getKsrq();
            Date existingJsrq = existingFp.getJsrq();
            boolean existingIsPermanent = existingJsrq.getTime() == 6879398400000L;

            if (isPermanent) {
                // 分配=2188 历史!=2188
                if (!existingIsPermanent) {
                    if (zzhFpgsKsrq.compareTo(existingJsrq) <= 0)
                        return R.error("分配时间段与历史分配时间重叠!");
                }
                // 分配=2188 历史=2188
                else {
                    if (zzhFpgsKsrq.compareTo(existingKsrq) <= 0)
                        return R.error("分配时间段与历史分配时间重叠!");
                }
            } else {
                // 分配!=2188  历史!=2188
                if (!existingIsPermanent) {
                    if (zzhFpgsKsrq.compareTo(existingJsrq) <= 0 &&
                            zzhFpgsJsrq.compareTo(existingKsrq) >= 0) {
                        return R.error("分配时间段与历史分配时间重叠!");
                    }
                }
                // 分配!=2188  历史=2188
                else {
                    if (zzhFpgsKsrq.compareTo(existingKsrq) == 0 || zzhFpgsJsrq.compareTo(existingKsrq) == 0) {
                        return R.error("分配时间段与历史分配时间重叠!");
                    }
                }
            }
        }

        if (fpList.size() > 0) {
            for (ZzhFpGsEntity existingFp : fpList) {
                if (existingFp.getJsrq().getTime() == 6879398400000L) {
                    if (existingFp.getKsrq().compareTo(zzhFpgsKsrq) < 0) {

                        // 另外根据分配的开始日期去查子账号分配客服,在这个时间之后有没有分配客服的记录
                        QueryWrapper<ZzhFpKfEntity> queryWrapper1 = new QueryWrapper<>();
                        queryWrapper1.lambda().eq(ZzhFpKfEntity::getFpGsId, existingFp.getFpGsId());
                        queryWrapper1.lambda().ge(ZzhFpKfEntity::getKsrq, zzhFpgsKsrq);
                        int count = zzhFpKfService.count(queryWrapper1);
                        if (count > 0) {
                            return R.error("分配失败,该日期已被分配客服！");
                        } else {
                            UpdateWrapper<ZzhFpKfEntity> updateWrapper = new UpdateWrapper<>();
                            updateWrapper.lambda()
                                    .eq(ZzhFpKfEntity::getFpGsId, existingFp.getFpGsId())
                                    .eq(ZzhFpKfEntity::getJsrq, DateUtils.stringToDate("2188-01-01", DateUtils.DATE_PATTERN))
                                    .set(ZzhFpKfEntity::getJsrq, DateUtils.addDateDays(zzhFpgsKsrq, -1));
                            zzhFpKfService.update(updateWrapper);
                        }

                        // 将历史永久记录的结束日期修改为当前开始日期的前一天
                        existingFp.setJsrq(DateUtils.addDateDays(zzhFpgsKsrq, -1));
                        this.updateById(existingFp);
                    } else {
                        return R.error("分配时间段与历史分配时间重叠!");
                    }
                }
            }
        }

        // 查看这个子账号在分配日期有没有绩效数据,如果有绩效数据则不允许分配公司
        UpdateWrapper<JxSjEntity> updateWrapper1 = new UpdateWrapper<>();
        updateWrapper1.lambda()
                .ge(JxSjEntity::getDate, zzhFpgsKsrq)
                .le(JxSjEntity::getDate, zzhFpgsJsrq)
                .set(JxSjEntity::getFpKfId, null);
        jxSjService.update(updateWrapper1);

        // 保存新记录
        Long userId = CommonUtils.getUserId();
        zzhFpGsEntity.setCreateUserId(userId);
        this.save(zzhFpGsEntity);
        return R.ok();
    }

    @Override
    public R postFpgsRevoke(ZzhFpGsEntity zzhFpGsEntity) {
        System.out.println(zzhFpGsEntity);
        Long fpGsId = zzhFpGsEntity.getFpGsId();
        QueryWrapper<ZzhFpKfEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ZzhFpKfEntity::getFpGsId, fpGsId);
        int count = zzhFpKfService.count(queryWrapper);
        if (count > 0) {
            return R.error("撤销失败，该公司分配记录已分配客服!");
        }

        // 删除这个分配公司的记录
        boolean removeFpGs = this.removeById(fpGsId);
        if (removeFpGs) {
            return R.ok();
        } else {
            return R.error("撤销失败");
        }
    }
}